/*
 * mbport_network.h
 *
 * Change Logs:
 * Date           Author       Notes
 * 2022-01-25     nx      	   the first version
 *
 */

#ifndef __MBPORT_NETWORK_H_
#define __MBPORT_NETWORK_H_

#include <string.h>
#include "rl_net.h"
#include "modbus_cfg.h"
#include "modbus_priv.h"

#ifdef __cplusplus
extern "C" {
#endif

#if (MODBUS_ETH_ENABLED > 0)

#define MBPORT_NET_DEFAULT_PORT             502

#define MOPORT_NET_ADU_SIZE_MAX             513

/* Modbus side define */
typedef enum mbport_net_side
{
    MBPORT_NET_CLIENT = 0x01,
    MBPORT_NET_SERVER = 0x02,
} mbport_net_side_t;

/* Modbus net protocol type */
typedef enum mbport_net_proto
{
    MBPORT_NET_TCP = 0x01,
    MBPORT_NET_UDP = 0x02,
} mbport_net_proto_t;


#define MBPORT_NET_CFG(cfg, lip, rip,   \
        gw, sm, lp, rp, ct)             \
    do {                                \
        (cfg)->local_ip = lip,          \
        (cfg)->remote_ip = rip,         \
        (cfg)->def_gw = gw;             \
        (cfg)->net_mask = sm;           \
        (cfg)->local_port = lp;         \
        (cfg)->remote_port = rp;        \
        (cfg)->connect_tmo = ct;        \
    } while(0)
    
    
#define NETWORK_DEFAULT_CFG         \
    {                               \
        "192.168.1.3",              \
        "192.168.1.2",              \
        "192.168.1.1",              \
        "255.255.255.0",            \
        502,                        \
        502,                        \
        3000,                       \
    }

typedef struct mbport_netcfg
{
	const mb_char_t *local_ip;          /* Local IP address */
    const mb_char_t *remote_ip;         /* Remote IP address */
    const mb_char_t *def_gw;            /* Default gateway */
    const mb_char_t *net_mask;          /* Netmask */

	mb_uint16_t local_port;             /* Local Port, default 502 */
    mb_uint16_t remote_port;            /* Remote Port, default 502 */
	mb_uint32_t connect_tmo;            /* Connect timeout, default 3000 ms */
} mbport_netcfg_t;


typedef struct mbport_network
{
    modbus_port_t parent;
    
    int side;
    int proto;
    int conn_tmo;
    int svr_sock;
    int con_sock;
    fd_set allset;
    struct timeval tval;
    struct sockaddr_in local_addr;
    struct sockaddr_in remote_addr;
    
    int (*send)(int sock, const char *buf, int len, int flags, const SOCKADDR *to, int tolen);
    int (*recv)(int sock, char *buf, int len, int flags, SOCKADDR *from, int *fromlen);
    
    /* Receive buffer */
    uint16_t count;
    uint16_t rd_pos;
    uint8_t buf[MOPORT_NET_ADU_SIZE_MAX];
        
} mbport_network_t;


mbport_network_t *mbport_network_create(mbport_net_side_t side, mbport_net_proto_t proto);

#endif

#ifdef __cplusplus
}
#endif

#endif

